import {AuthButton, ProTable} from '@/components'
import supplierStore from '@/pages/base/supplier/store'
import userStore from '@/pages/system/account/store'
import {DeleteOutlined} from '@ant-design/icons'
import {Button, DatePicker, Descriptions, Form, Input, message, Select, Tooltip} from 'antd'
import dayjs from 'dayjs'
import {http, includes} from 'libs'
import {observer} from 'mobx-react'
import React, {useEffect, useState} from 'react'
import {useParams} from 'react-router-dom'
import store from './store'

const defArr = Array(50).fill({}).map((_, index) => ({id: index}))
export default observer(function () {
  const id = useParams().id
  const [form1] = Form.useForm()
  const [form2] = Form.useForm()
  const snRef = React.useRef(1)
  const [loading, setLoading] = useState(false)
  const [data, setData] = useState([{}])
  const sn = 'CDD' + dayjs().format('-YYYY-MM-DD-') + snRef.current.toString().padStart(4, '0')
  const w = {width: 150}
  const readOnly = store.record.id
  const columns = [
    {
      title: 'No.',
      key: 'series',
      width: 44,
      render: (_, __, index) => <span className="idx">{index + 1}</span>,
    }, {
      title: '商品编号',
      dataIndex: ['product', 'sn'],
      modal: 'product',
      name: 'sn',
      readOnly,
      onChange: (info, val) => handeEdit(info, 'product', val),
    }, {
      title: '商品全名',
      dataIndex: ['product', 'name'],
      modal: 'product',
      name: 'name',
      readOnly,
      onChange: (info, val) => handeEdit(info, 'product', val),
    }, {
      title: '仓库全名',
      dataIndex: ['warehouse', 'name'],
      modal: 'warehouse',
      name: 'name',
      readOnly,
      onChange: (info, val) => handeEdit(info, 'warehouse', val),
    }, {
      title: '数量',
      dataIndex: 'quantity',
      type: 'number',
      readOnly,
      onChange: (info, val) => handeEdit(info, 'quantity', val),
    }, {
      title: '单价',
      dataIndex: 'price',
      type: 'number',
      readOnly,
      onChange: (info, val) => handeEdit(info, 'price', val),
    }, {
      title: '金额',
      render: i => typeof i.price === 'number' && typeof i.quantity === 'number' && i.price * i.quantity,
    }, {
      title: '单据备注',
      dataIndex: 'remarks',
      type: 'text',
      readOnly,
      onChange: (info, val) => handeEdit(info, 'remarks', val),
    }, {
      title: '删除',
      width: 50,
      align: 'center',
      render: info => (
        <Tooltip title="删除本行" placement="left">
          <AuthButton
            type="link"
            className="delBtn"
            icon={<DeleteOutlined/>}
            onClick={() => handleDelete(info)}/>
        </Tooltip>
      ),
    }]

  useEffect(() => {
    !userStore.records.length && userStore.fetchRecords()
    !supplierStore.records.length && supplierStore.fetchRecords()
  }, [])

  useEffect(() => {
    if (id) {
      store.fetchRecord(id)
    } else {
      store.set('record', {})
      setData([...defArr])
      form1.resetFields()
      form2.resetFields()
    }
  }, [id])

  useEffect(() => {
    if (!store.record.id) return
    console.log('Store.record=', JSON.stringify(store.record))
    setData(store.record.entries.map(x => ({
      id: x.id,
      product: x.product,
      warehouse: x.warehouse,
      price: x.price,
      quantity: x.quantity,
      freight: x.freight,
      remarks: x.remarks,
    })))

    form1.setFieldsValue({
      date: dayjs(store.record?.created_at ?? ''),
      sn: store.record.sn,
    })
    form2.setFieldsValue({
      handler_id: store.record.handler_id,
      supplier_id: store.record.supplier_id,
      remarks: store.record.remarks,
    })

  }, [store.record])

  // 修改单元格数据
  function handeEdit(info, name, value) {
    setData(data.map(x => x.id === info.id ? {...x, [name]: value} : x))
    // console.log("Value=", value)
    // console.log("Data=", JSON.stringify(data))
  }

  // 删除当前行
  function handleDelete(info) {
    setData(data.filter(x => x.id !== info.id))
  }

  // 提交
  function handleSubmit() {
    form2.validateFields().then(values => {
      let tableData = data.filter(v => v['product']?.id && v['warehouse']?.id)
      console.log('TableData=', tableData)
      if (!tableData.length) {
        message.error('请添加商品')
        return
      }
      let ajaxData = {
        ...values,
        entries: tableData.map(v => ({
          product_id: v['product']?.id,
          warehouse_id: v['warehouse']?.id,
          price: v.price,
          quantity: v.quantity,
          freight: v.freight,
          remarks: v.remarks,
        })),
      }
      setLoading(true)
      http.post('/api/purchase/return/', ajaxData)
        .then(() => {
          handleReset()
          message.success('操作成功')
        })
        .finally(() => setLoading(false))
    })
  }

  // 重置整个页面
  function handleReset() {
    let cur = data.map(v => ({id: v.id}))
    setData([...cur])
    form2.resetFields()
  }

  return (
    <ProTable
      columns={store.record.id ? columns.slice(0, -1) : columns}
      dataSource={data}
      header={<>
        <div className="title1">采购退货单</div>
        <Form form={form1}
              disabled
              layout="inline"
              labelCol={{flex: '7em'}}
              initialValues={{date: dayjs(), sn}}>
          <Form.Item name="date" label="业务日期" required>
            <DatePicker rootClassName="noBrd"/>
          </Form.Item>
          <Form.Item name="sn" label="单据编号" required style={{marginRight: 0, width: 230}}>
            <Input rootClassName="noBrd" style={{width: '100%'}}/>
          </Form.Item>
        </Form>
      </>
      }
      params={<Form form={form2}
                    disabled={readOnly}
                    layout="inline"
                    labelCol={{flex: '7em'}}
                    initialValues={{date: dayjs()}}>
        <Form.Item name="supplier_id" label="往来单位" rules={[{required: true, message: '请选择往来单位'}]}>
          <Select style={w}
                  rootClassName="brdB"
                  options={supplierStore.records}
                  fieldNames={{label: 'name', value: 'id'}}
                  showSearch
                  filterOption={(input, option) => includes(option.name, input)}
          />
        </Form.Item>
        <Form.Item name="handler_id" label="经手人" rules={[{required: true, message: '请选择经手人'}]}>
          <Select style={w}
                  rootClassName="brdB"
                  options={userStore.records}
                  fieldNames={{label: 'nickname', value: 'id'}}
                  showSearch
                  filterOption={(input, option) => includes(option.nickname, input)}
          />
        </Form.Item>
        <Form.Item name="remarks" label="摘要">
          <Input.TextArea
            rootClassName="brdB"
            autoSize={{minRows: 1}}
            style={{width: 300}}/>
        </Form.Item>
      </Form>
      }
      summary={<Descriptions column={5}>
        <Descriptions.Item label="制单人">
          {store.record.crated_by ? store.record.crated_by?.nickname : localStorage.getItem('nickname')}
        </Descriptions.Item>
        <Descriptions.Item label="合计数量">
          {data.reduce((a, b) => a + (b.quantity || 0), 0) || ''}
        </Descriptions.Item>
        <Descriptions.Item label="合计金额">
          {data.reduce((a, b) => a + (b.price * b.quantity || 0) + (b.freight || 0), 0) || ''}
        </Descriptions.Item>
      </Descriptions>}
      actions={<>
        <Button type="primary" onClick={handleSubmit} loading={loading}>完成</Button>
        <Button onClick={handleReset} disabled={loading}>关闭</Button>
      </>
      }
    />
  )
})
